//skeleton-plugin.js
//引入html-webpack-plugin插件
// const HtmlWebpackPlugin = require('html-webpack-plugin');
const cheerio = require('cheerio');
const fs = require("fs");

const DEFAULT_PLUGIN_OPTIONS = {
    root: '#app',
    HtmlWebpackPlugin: require('html-webpack-plugin')
};

class SkeletonPlugin {
    constructor(options = {}) {
        this.options = Object.assign({}, DEFAULT_PLUGIN_OPTIONS, options);
    }
    apply(compiler) {
        // 我们这里监听compilation钩子函数，目的是编译创建之后，执行我们的SkeletonPlugin插件的主要代码
        compiler.hooks.compilation.tap('skeleton-webpack5-plugin', (compilation) => {
            //在html-webpack-plugin插件生成资源到output目录之前，我们完成对骨架屏代码的插入
            this.options.HtmlWebpackPlugin.getHooks(compilation).beforeEmit.tapAsync(
                'skeleton-webpack5-plugin',
                (htmlData, cb) => {
                    const template = fs.readFileSync(this.options.url, "utf-8");
                    const $ = cheerio.load(htmlData.html);
                    $(this.options.root).html(template)

                    htmlData.html = $.html();
                    //最后执行cb回调，告诉webpack，我们的插件已经操作完成，让它继续执行其他的操作
                    cb(null, htmlData)
                }
            )
        });

    }
}

//导出SkeletonPlugin插件
module.exports = SkeletonPlugin;
